package so.ifl.manager.admin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.web.DoradoContext;

import so.ifl.commons.tools.Constant;
import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.DoradoSystemUtils;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.except.SessionTimeOutException;
import so.ifl.commons.tools.xml.XMLStringParser;
import so.ifl.servcie.ReportService;
import so.ifl.servcie.StudentService;
import so.ifl.vo.AccountVo;
import so.ifl.vo.MappingVo;
import so.ifl.vo.PayRecordVo;
import so.ifl.vo.ResultVo;
import so.ifl.vo.StudentVo;

/**
 * 学员信息manager
 * create by simon
 * create at 2012-1-10 下午10:29:29
 * <mailto:liangyuanliu@gmail.com>
 */
@Component("studentManager")
public class StudentManager {
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private ReportService  reportService;

	private Logger logger_ = LoggerFactory.getLogger(this.getClass());


	/**
	 * 学员信息分布查询
	 * simon
	 * create at 2012-1-10 下午9:54:10
	 * <mailto:liangyuanliu@gmail.com>
	 * @param page
	 * @param map
	 */
	@DataProvider
	public void getStudent(Page<StudentVo> page, Map<String, Object> map) {
		int offset = page.getFirstEntityIndex();
		int limmit = page.getPageSize();
		if (map == null) {
			map = new HashMap<String, Object>();
		}

		AccountVo accountVo = DoradoSystemUtils.getCurrentUser(DoradoContext.getCurrent().getRequest());
		if (null != accountVo && null !=  accountVo.getAccoutId()) {
			map.put("company_id", accountVo.getCompanyId());
			
			map.put("data_stutas_", Constant.INT_TRUE_VALUE);//只查询数据状态为正常的数据
			
			List<StudentVo> list = studentService.queryStudentWithParamAndPagination(map, offset, limmit);
			int countsql = studentService.countStudentWithParam(map);
			page.setEntities(list);
			page.setEntityCount(countsql);
		}else{
			logger_.error("登录超时。。");
			
			page.setEntities(new ArrayList<StudentVo>());
			page.setEntityCount(0);
		}
		
		
	}

	/**
	 * 学员信息cud
	 * simon
	 * create at 2012-1-10 下午10:29:08
	 * <mailto:liangyuanliu@gmail.com>
	 * @param students
	 */
	@DataResolver
	public void updatetudent(Collection<StudentVo> students) {
		for (StudentVo student : students) {
			EntityState entityState = EntityUtils.getState(student);
			if (EntityState.NEW.equals(entityState)) {
				// 新增
				logger_.info("新增");
				insertStudent(student);
			} else if (EntityState.MODIFIED.equals(entityState)) {
				// 修改
				logger_.info("修改");
				updateStudent(student);
			} else if (EntityState.DELETED.equals(entityState)) {
				// 删除
				logger_.info("删除");
				deleteStudent(student.getStudentId());
			}
		}
	}
	
	/**
	 * 查询成绩单
	 * create by aaron.lu
	 * create at 2012-1-18 下午9:46:02
	 * <mailto: atyuan.lu@gmail.com>
	 * @param params
	 * @return
	 *
	 */
	@DataProvider
	public List<ResultVo> queryResultOfStudent(Map<String, Object> params){
		logger_.debug("queryResultOfStudent with params = " + params);
		Integer studentId = (Integer)params.get("studentId");
		if (StringHelper.isNotEmpty(studentId.toString())) {
			return studentService.queryResult(studentId.toString());
		}
		
		return new ArrayList<ResultVo>();
	}
	
	/**
	 * 
	 * create by aaron.lu
	 * create at 2012-1-18 下午9:46:59
	 * <mailto: atyuan.lu@gmail.com>
	 *
	 */
	@Expose
	public Map<String, Object> editResultOfStudent(String type, String result,String source, String studentId){
		Map<String, Object> re = new HashMap<String, Object>();
		String flag = Constant.SUCCESS_TRUE_FLAG;
		
		try {
			studentService.saveEditOfResult(type, result, source, studentId);
		} catch (Exception e) {
			logger_.error(e.getMessage());
			flag = Constant.SUCCESS_FALSE_FLAG;
		}
		
		re.put("flag", flag);
		
		return re;
	}
	
	/**
	 * 保存成绩表
	 * create by aaron.lu
	 * create at 2012-1-19 上午9:12:56
	 * <mailto: atyuan.lu@gmail.com>
	 * @param resultVos
	 *
	 */
	@DataResolver
	public void saveResult(Collection<ResultVo> resultVos){
		for (ResultVo resultVo : resultVos) {
			EntityState entityState = EntityUtils.getState(resultVo);
			if (EntityState.NEW.equals(entityState) || EntityState.MODIFIED.equals(entityState)) {
				studentService.saveResult(resultVo);
			}
		}
	}
	
	/**
	 * 获取付款记录
	 * create by aaron.lu
	 * create at 2012-1-19 上午10:18:42
	 * <mailto: atyuan.lu@gmail.com>
	 * @param page
	 * @param params
	 *
	 */
	@DataProvider
	public void getPayRecord(Page<PayRecordVo> page, Map<String, Object> params) {
		int offset = page.getFirstEntityIndex();
		int limmit = page.getPageSize();
		if (params == null) {
			params = new HashMap<String, Object>();
		}

		AccountVo accountVo = DoradoSystemUtils.getCurrentUser(DoradoContext.getCurrent().getRequest());
		if (null != accountVo && null !=  accountVo.getAccoutId()) {
			params.put("company_id", accountVo.getCompanyId());
		}else{
			throw new SessionTimeOutException("登录超时。。");
		}
		
		List<PayRecordVo> list = studentService.queryPayRecordOfStudent(params, offset, limmit);
		int total = studentService.countPayRecord(params);
		page.setEntities(list);
		page.setEntityCount(total);
	}
	
	/**
	 * 保存付款记录
	 * create by aaron.lu
	 * create at 2012-1-19 上午10:23:10
	 * <mailto: atyuan.lu@gmail.com>
	 * @param recordVos
	 *
	 */
	@DataResolver
	public void updatePayRecord(Collection<PayRecordVo> recordVos) {
		for (PayRecordVo payRecordVo : recordVos) {
			EntityState entityState = EntityUtils.getState(payRecordVo);
			if (EntityState.NEW.equals(entityState)) {
				// 新增
				logger_.info("新增");
				studentService.insertPayRecord(payRecordVo);
			} else if (EntityState.MODIFIED.equals(entityState)) {
				// 修改
				logger_.info("修改");
				studentService.updatePayRecord(payRecordVo);
			} else if (EntityState.DELETED.equals(entityState)) {
				// 删除
				logger_.info("删除");
				studentService.deletePayRecord(payRecordVo.getRecordId());
			}
		}
	}
	
	/**
	 * 获取匹配信息
	 * create by aaron.lu
	 * create at 2012-3-29 下午11:49:07
	 * <mailto: atyuan.lu@gmail.com>
	 * @return
	 *
	 */
	@DataProvider
	public void getResidenceMapping(Page<MappingVo> page, Map<String, Object> params){
		int offset = page.getFirstEntityIndex();
		int limmit = page.getPageSize();
		if (params == null) {
			params = new HashMap<String, Object>();
		}
		params.put("group_", "djzs");//只拿登记住所的匹配
		
		List<MappingVo> list = studentService.getMapping(params, limmit, offset);
		int total = studentService.countMapping(params);
		page.setEntities(list);
		page.setEntityCount(total);
	}
	
	/**
	 * 调用服务接口查询身份证信息
	 * create by aaron.lu
	 * create at 2012-3-18 上午10:58:28
	 * <mailto: atyuan.lu@gmail.com>
	 * @param question
	 * @return
	 *
	 */
	@Expose
	public Map<String, Object> ajaxActionGetCertInfo(String question){
		Map<String, Object> rs = new HashMap<String, Object>();
		
		
		if (StringHelper.isNotEmpty(question)) {
			
			
			
			
			
			
			
			String spec  = "http://www.youdao.com/smartresult-xml/search.s?type=id&q=" + question;
			
			
			//调用rest service
			try {
				URL url = new URL(spec);
				HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
				InputStream in = urlConn.getInputStream();   
			    String rs_string = InputStreamToString(in, "gbk"); 
			    
			    rs = XMLStringParser.parseXMLString(rs_string);
			    
			    String birthday = (String)rs.get("birthday");
			    String gender = (String)rs.get("gender");
			    if (StringHelper.isNotEmpty(birthday)) {
					try {
						Date t = DateUtil.YMD_SDF_M.parse(birthday);
						String finalv = DateUtil.YMD_SDF.format(t);
						rs.put("birthday", finalv);
					} catch (ParseException e) {
						logger_.error(e.getMessage());
					}
					
				}
			    
			    if (StringHelper.isNotEmpty(gender)) {
			        String gender_ = "1";
					if (gender.equals("f")) {
						gender_ = "0";
					}
					rs.put("gender", gender_);
				}
			    
			    if (question.length() > 6) {
					String studentResidence = question.substring(0, 6);
					String studentResidenceV = "";
					Map<String, Object> queryMappingParams = new HashMap<String, Object>();
					queryMappingParams.put("group_", "djzs");
					queryMappingParams.put("key_", studentResidence);
					List<MappingVo> mappingVos = studentService.getMapping(queryMappingParams);
					
					
					if (null != mappingVos && mappingVos.size() > 0) {
						studentResidence = mappingVos.get(0).getKeyv();
						studentResidenceV = mappingVos.get(0).getValuev();
					}else{
						studentResidence = "";
						studentResidenceV = "";
					}
					
					rs.put("studentResidence", studentResidence);
					rs.put("studentResidenceV", studentResidenceV);
				}
			    
			    logger_.debug("rs:" + rs);
				
				
			} catch (MalformedURLException e) {
				logger_.error(e.getMessage() + ":" + e.getCause());
			} catch (IOException e) {
				logger_.error(e.getMessage() + ":" + e.getCause());
			} catch (SAXException e) {
				logger_.error(e.getMessage() + ":" + e.getCause());
			} catch (ParserConfigurationException e) {
				logger_.error(e.getMessage() + ":" + e.getCause());
			}
			
		}else{
			logger_.error("question is null...");
		}
		
		

		
		return rs;
	}
	
	

	/**
	 * 新增学员信息
	 * simon
	 * create at 2012-1-10 下午10:28:18
	 * <mailto:liangyuanliu@gmail.com>
	 * @param student
	 */
	private void insertStudent(StudentVo student) {
		
		AccountVo accountVo = DoradoSystemUtils.getCurrentUser(DoradoContext.getCurrent().getRequest());
		if (null != accountVo && null !=  accountVo.getAccoutId()) {
			student.setCreateUser(accountVo.getAccountLoginName());
			student.setCreateTime(new Date());
			student.setLastModifyTime(new Date());
			student.setLastModifyUser(accountVo.getAccountLoginName());
			
			//设置所属的公司数据
			student.setCompanyId(accountVo.getCompanyId());
			student.setAccoutId(accountVo.getAccoutId());
			
			student.setDataStutas(Constant.INT_TRUE_VALUE);//初始数据状态是生效
		}else{
			throw new SessionTimeOutException("登录超时。。");
		}
		
		studentService.insertStudent(student);
	}
	/**
	 * 删除学员信息
	 * simon
	 * create at 2012-1-10 下午10:28:33
	 * <mailto:liangyuanliu@gmail.com>
	 * @param studentId
	 */
	private void deleteStudent(Integer studentId)
	{
		studentService.deleteStudent(studentId);		
	}
	
	/**
	 * 修改学员信息
	 * simon
	 * create at 2012-1-10 下午10:28:45
	 * <mailto:liangyuanliu@gmail.com>
	 * @param student
	 */
	private void updateStudent(StudentVo student)
	{
		
		AccountVo accountVo = DoradoSystemUtils.getCurrentUser(DoradoContext.getCurrent().getRequest());
		if (null != accountVo && null !=  accountVo.getAccoutId()) {
			student.setLastModifyTime(new Date());
			student.setLastModifyUser(accountVo.getAccountLoginName());
		}else{
			throw new SessionTimeOutException("登录超时。。");
		}
		
		studentService.updateStudent(student);
	}
	
	
	
	/**  
	* 将InputStream转换成String  
	* @param urlStr  
	* @param charsetName  字符集名  
	* @return  
	*/  
	private String InputStreamToString ( InputStream in, String charsetName) {   
	      
	    if (in == null) {   
	        return null;   
	    }   
	    StringBuilder sb = new StringBuilder();   
	    String temp = null;   
	    try {   
	        BufferedReader bf = new BufferedReader(new InputStreamReader(in, charsetName));   
	        while ((temp = bf.readLine()) != null) {   
	            sb.append(temp).append("\n");   
	        }   
	    } catch (IOException e) {   
	        e.printStackTrace();   
	    }   
	    return sb.toString();   
	}  

}
